package com.bbseguros.pesquisador.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

public class ImageCreator {

	private static final long serialVersionUID = 1L;
	private static BufferedImage image = null;
	private String text;
	private String outputFileName;
	private static Logger logger = Logger.getLogger(ImageCreator.class);
	
    public ImageCreator (String sourceFile, String destFile, String text) throws IOException {
    	setOutputFileName(destFile);
    	setText(text);
    	image = ImageIO.read(new File(sourceFile));
    }	
	
    public void generateImage() {
        drawText(image);
        save(image);
    }
 
    private void drawText(BufferedImage image) {
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        Font font = g2.getFont().deriveFont(36f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        float width = (float)font.getStringBounds(text, frc).getWidth();
        LineMetrics lm = font.getLineMetrics(text, frc);
        float height = lm.getAscent() + lm.getDescent();
        float x = (image.getWidth() - width)/2f;
        float y = (image.getHeight() + height)/2f - lm.getDescent();
        g2.setPaint(Color.BLACK);
        g2.drawString(text, x, y);
        g2.dispose();
    }
 
    private File save(BufferedImage image) {
        String ext = "png";   // bmp, gif, png okay in j2se 1.6
        File file = new File(getOutputFileName());
        
        try {
            ImageIO.write(image, ext, file);
        } catch(IOException e) {
            logger.error(e.getMessage(), e);
        }
        return file;
    }

    public String getOutputFileName() {
		return outputFileName;
	}

	public void setOutputFileName(String outputFileName) {
		this.outputFileName = outputFileName;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
}

